package com.example.springsecurity.sericice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * 重写登录逻辑
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService { //实现该接口

    @Autowired
    private PasswordEncoder pw;

    @Override   //重写这个方法,这个就是登录逻辑
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.查询数据库判断用户是否存在,如果不存在抛出UsernameNotFoundException
        if("normal".equals(username)){     //模拟从数据库拿到的用户名

            //2.把查询出来的密码进行对比
            String password = pw.encode("normal"); //用来模拟从数据库查找到的密码
//            return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));//赋予权限
            return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_normal"));//赋予权限
        }
        else if ("admin".equals(username)){
            String password = pw.encode("admin"); //用来模拟从数据库查找到的密码
            return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin"));//赋予权限

        }else if("test".equals(username)){
            String password = pw.encode("test"); //用来模拟从数据库查找到的密码
            return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_test"));//赋予权限

        }
        else  throw new UsernameNotFoundException("用户不存在");
    }


}
